/*
 * @Author: lp
 * @Date: 2022-01-14 10:21:11
 * @LastEditTime: 2022-06-14 17:14:43
 * @LastEditors: lp 654528967@qq.com
 * @Description: 路由守卫
 * @FilePath: \nien-vue3-admin\src\router\navigationGuard.ts
 */
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Router, RouteRecordRaw } from 'vue-router'
import { getToken } from '@/utils/auth'
import userStore from '@/store/modules/user'
// import useRouters from '@/store/modules/router'

const whiteList = ['/login/signIn', '/login/resetPswd', '/login']
export default function (router: Router) {
  router.beforeEach(async (to, from) => {
    const user = userStore()
    // const routers = useRouters()
    NProgress.configure({ showSpinner: false })
    NProgress.start()
    const token = getToken()
    // debugger
    try {
      if (token) {
        if ((to.path === '/login/signIn' && from.path != '/login/signIn') || (to.path === '/login/resetPswd' && from.path != '/login/resetPswd')) {
          NProgress.done()
          return { path: '/' }
        } 
        if (!user.company && to.name !== 'selectCompany') return { name: 'selectCompany' } 
        if (user.roles.length === 0) {
          await user.getInfo()
          const accessRoutes: RouteRecordRaw[] = await user.generateRoutes()
          for (const route of accessRoutes) {
            router.addRoute(route)
          }
          NProgress.done()
          user.setLoginLoading(false) 
          return { ...to, replace: true }
        } 
        NProgress.done()
        return true
      } 
      // 白名单
      if (whiteList.indexOf(to.path) !== -1) return true
      return { path: '/login/signIn', query: { redirect: to.fullPath }, replace: true }
    } catch (err) {
      await user.fedLogOut()
      user.setLoginLoading(false) 
      return { path: '/login/signIn', query: { redirect: to.fullPath }, replace: true }
    }
  })
  router.afterEach(() => {
    NProgress.done()
  })
}
